package com.hushan.elevator.security;

import com.hushan.elevator.dao.RoleRepository;
import com.hushan.elevator.dao.UserRepository;
import com.hushan.elevator.model.Role;
import com.hushan.elevator.model.User;
import jakarta.annotation.Resource;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class DBUserDetailsService implements UserDetailsService {
    @Resource
    private UserRepository userDao;
    @Resource
    private RoleRepository roleDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userDao.findByTelNumb(username).orElseThrow(() -> new UsernameNotFoundException(username));
        List<String> authorities = new ArrayList<>();
        Role role = roleDao.findRoleByUser(user.getUserId());
        if (role != null) {
            authorities.add(role.getRoleAuth());
        }
        return new MyUserDetail(user,authorities,null);
    }
}
